<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"  xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head th:replace="_header_include::frag(~{::title},~{::style},~{})">
    <title>后台管理系统</title>
    <meta charset="UTF-8">
    <!-- import CSS -->
    <link rel="stylesheet" href="css/element-ui.css">
    <link rel="stylesheet" href="css/base.css">
    <style>
        .f-tac .el-form-item__content{
            margin-left: 0 !important;
        }
        .el-cascader {
            width: 200px;
        }
    </style>
</head>
<body>
<div id="recordPaymentOffline" class="recordPaymentOffline mainPadding" style="display: none;">
    <!-- <el-breadcrumb separator="/" class="elBreadcrumb marginB20">
        <el-breadcrumb-item>Home</el-breadcrumb-item>
        <el-breadcrumb-item>充值管理</el-breadcrumb-item>
        <el-breadcrumb-item>录入线下充值</el-breadcrumb-item>
    </el-breadcrumb> -->
    <!-- <div class="inforTitle">录入线下充值</div>  -->
    <el-form :model="form" ref="form" :rules="rules" :label-width="formLabelWidth">
        <el-row class="borderbox padding20" style="border: none !important;">
            <el-form-item label="充值商家：" prop="rechargeBusiness">
                    <!-- <el-select v-model="form.rechargeBusiness" filterable  clearable placeholder="商家账户名">
                        <el-option
                            v-for="item in merchantUserListOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select> -->

                    <el-cascader
                        v-model="form.rechargeBusiness"
                        :options="options"
                        filterable
                        clearable
                        @active-item-change="handleChange"  
                        popper-class="refSubCat"   
                        @focus="cascaderfocus" 
                        @change="cascaderChange"                 
                        
                    >
            
                </el-cascader>
                  


                </el-form-item>
            <el-form-item label="充值金额：" prop="rechargeMoney">
                <el-input v-model="form.rechargeMoney" placeholder="1-999999" style="width: 250px;" maxLength="7" @keyup.native="number"></el-input>                    
            </el-form-item>
            <el-form-item label="图片证明：" prop="fileList" style="width: 500px;">
                <el-upload
                    class="upload-demo"
                    :action="uploadOssHost"
                    ref="refundApplyImgUpload"
                    :on-preview="handlePreview"
                    :on-remove="handleRemove"
                    :on-success="handleSuccess"
                    :on-error="handleError"
                    :before-upload="handleBefore"
                    accept=".jpg,.png"
                    multiple
                    :data="uploadParamData"
                    :limit='1'
                    :on-change="selectFile"
                    :on-exceed="handleExceed"
                    :auto-upload="false"
                    :file-list="fileList">
                    <el-button slot="trigger" size="small" type="primary">选择图片</el-button>
                    <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传</el-button>
                    <div slot="tip" class="el-upload__tip">支持图片大小2M以内，jpg/jpeg/png格式的图片</div>
                </el-upload>                   
            </el-form-item>

        

            <div class="f-tac">
                <el-form-item>
                    <el-button type="primary" @click="submitForm('form')" :disabled="isDisabled">保存</el-button>
                    <el-button @click="cancel">取消</el-button>
                </el-form-item>
            </div>
        </el-row>
        
    </el-form>
</div>
</body>
<!-- import Vue before Element -->
<div th:include="_footer_include :: #jsLib"></div>
<!-- import common js-->
<script th:inline="javascript">
    var ossSignatureUrl = [[${ossUrl}]];//上传文件地址
    var merchantUserList=[[${merchantUserList}]];//商户集合
    var token = [[${token}]];

    const options = merchantUserList.map(item => {
        const subChildren = item.children || [];
        const children = subChildren.map(subItem => {
            return {
                label: subItem.projectName, value: subItem.id
            }

        })
        const params = {
            label: item.name,
            value: item.id
        }
        if(subChildren.length) {
            params.children = children;
        }
        return params;
    })
    



    var addClueVM = new Vue({
        el: '#recordPaymentOffline',
        data: function() {
            return {
                isDisabled:false,
                merchantUserListOptions:merchantUserList,
                form: {
                    rechargeMoney: '',
                    fileList: [],  
                    imgUrl:'',
                    rechargeBusiness: []
                },
                rules:{
                    rechargeBusiness: [
                        { required: true, message: '请选择充值商家', trigger: 'blur' }
                    ],
                    rechargeMoney: [
                        { required: true, message: '请输入充值金额', trigger: 'blur' },
                        { validator:function(rule,value,callback){
                            // var reg =  /^[0-9]+[0-9]*]*$/ ;
                            var reg =  /^\+?[1-9][0-9]*$/ ;
                            if(value !=null && value !="null" && value !="" && !reg.test(value) ){
                                callback(new Error("请输入正整数"));
                                return;
                            }else{
                                callback();
                            }
                        }, trigger: 'blur'}
                    ],
                    fileList: [
                        { required: true, message: '请上传图片', trigger: 'change' }
                    ],
                },
                formLabelWidth:'150px',
                uploadOssHost:'',
                uploadParamData: {
                    key:'22',
                    policy:'',
                    OSSAccessKeyId:'',
                    success_action_status : '200', //让服务端返回200,不然，默认会返回204
                    signature:'', 
                    'x:params':'',
                    'realName':''
                },
                fileList:[],
                limit:1,
                ossUrl:ossSignatureUrl,
                options: options,
                dialogVisible: false,
                timer: null
            }
        },
        methods: {
            cancel(){
                parent.window.ocmVM.chindRenClick()
                // window.location.href="/merchant/merchantRechargeRecordManage/initRechargeRecordManage"
            },
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.isDisabled=true;
                        var param ={};   
                        param.rechargeBusiness = this.form.rechargeBusiness[0];
                        param.rechargeMoney = this.form.rechargeMoney; 
                        param.imgUrl = this.form.imgUrl;
                        //param.token = token;
                        console.log(param)
                        axios.post('/merchant/merchantRechargeRecordManage/saveOfflinePayment', param)
                        .then(function (response) {
                            console.log(response)
                            var result =  response.data;
                            if(result.code=="0"){
                                parent.window.ocmVM.chindRenClick()
                                // window.location.href="/merchant/merchantRechargeRecordManage/initRechargeRecordManage"    
                            }else{
                                addClueVM.isDisabled=false;
                                addClueVM.$message.error(result.msg);
                            }           
                        })
                        .catch(function (error) {
                             console.log(error);
                        });
                    } else {
                        console.log('error submit!!');
                    return false;
                    }
                });
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            getUploadParam(){
                var signUrl = this.ossUrl+"?serviceType=aggregation";
                var param={};
                
                 axios.get(signUrl, param)
                .then(function (response) {
                   // console.info(response);
                    var respData= response.data;
                    var host = respData.host;
                    var params={};
                    var new_multipart_params = {
                            dir:respData.dir,
                            'policy': respData.policy,
                            'OSSAccessKeyId': respData.accessid,
                            'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
                            'signature': respData.signature,
                            'x:params':params,//自定义编码，basse64编码后的字符串,
                            'realName':''
                   };
                  addClueVM.uploadParamData= new_multipart_params;
                  addClueVM.uploadOssHost = host;
                })
                .catch(function (error) {
                     console.log(error);
                });
            },
            selectFile(file, fileList){
                addClueVM.uploadParamData.key= addClueVM.uploadParamData.dir+addClueVM.random_string(10)+addClueVM.get_suffix(file.name),
                addClueVM.uploadParamData.realName= file.name
            },
            submitUpload(){
                //this.customUpload();
                this.$refs.refundApplyImgUpload.submit();
            },
            handlePreview(file){
             
            },
            handleRemove(file,fileList){
                this.fileList=[];
                this.form.fileList=[];
            },
            handleExceed(files, fileList) {
             //this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
            },
            handleSuccess(response, file, fileList){                
                var realName = file.name;
                var randomName = addClueVM.uploadParamData.key;
                var imgUrl =  addClueVM.uploadOssHost+"/"+randomName;
                this.form.imgUrl=imgUrl;
                // this.form.fileList.push(realName);
                this.form.fileList=fileList;
                console.info(fileList);
                // this.fileList=[];
                // this.form.fileList=[];
            },
            handleError(err, file, fileList){
                console.info(err);
            },
            handleBefore(file){
                var isTextComputer = file.type === 'image/png' || file.type==='image/jpeg';
                if(!isTextComputer){
                   this.fileList=[];
                   this.$message.error('文件格式错误');
                   return false;
                }
                if(file.size>2*1024*1024){
                   this.fileList=[];
                   this.$message.error('图片最大为2MB');
                   return false;
                }
            },
            random_string(len) {
                len = len || 32;
                var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
                var maxPos = chars.length;
                var pwd = '';
                for (i = 0; i < len; i++) {
                    pwd += chars.charAt(Math.floor(Math.random() * maxPos));
                }
                return pwd;
            },
            get_suffix(filename) {
                var pos = filename.lastIndexOf('.')
                suffix = ''
                if (pos != -1) {
                   suffix = filename.substring(pos);
                }
                return suffix;
            },
            number(){
            　　this.form.rechargeMoney=this.form.rechargeMoney.replace(/[^\.\d]/g,'');
                this.form.rechargeMoney=this.form.rechargeMoney.replace('.','');
            },
            handleChange(value) { 
        
                this.form.rechargeBusiness = [value[0]];
        
                this.timer = setTimeout(() => {
                    document.getElementsByClassName('refSubCat')[0].style.display = 'none';
                    clearInterval(this.timer)
                }, 500)
                
                

            },
            cascaderfocus(value) {
                if(document.getElementsByClassName('refSubCat')[0] && document.getElementsByClassName('refSubCat')[0].style) {
                    document.getElementsByClassName('refSubCat')[0].style.display = 'block';
                }
                
            },
            cascaderChange(value) {
                this.form.rechargeBusiness = [value[0]];
            }
        },
        created(){
            this.getUploadParam();
        },
        mounted(){
            document.getElementById('recordPaymentOffline').style.display = 'block';
        }
  })
</script>
</html>